package com.relax.zk;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import org.apache.zookeeper.ZooDefs.Ids;

import java.util.List;

@SpringBootTest
public class ZKTest {

    private ZooKeeper zk;

    /**
     * 获取ZooKeeper链接
     */
    @Before
    public void getZKConnection() throws Exception {
        zk = new ZooKeeper("192.168.64.4:2181", 5000, null);
    }

    /**
     * 关闭ZK连接
     */
    @After
    public void closeZKConnection() throws InterruptedException {
        zk.close();
    }


    /**
     * 创建持久不带序列编号的节点
     */
    @Test
    public void createZKNode1() throws Exception {
        // 四个参数： 节点路径，节点数据，权限信息，节点的类型
        String result = zk.create("/zk", "zk_Data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("创建节点的结果" + result);
    }

    //创建持久带序列编号的节点
    @Test
    public void createZKNode2() throws Exception {
        // 四个参数： 节点路径，节点数据，权限信息，节点的类型
        zk.create("/zk", "zk_Data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        zk.create("/zk", "zk_Data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        zk.create("/zk", "zk_Data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
    }


    //创建临时不带序列编号的节点
    @Test
    public void createZKNode3() throws Exception {
        // 四个参数： 节点路径，节点数据，权限信息，节点的类型
        zk.create("/zk_e", "zk_Data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        Thread.sleep(30000);
    }


    //查看节点数据
    @Test
    public void getZNodeData() throws Exception {
        byte[] data = zk.getData("/zk", false, null);
        System.out.println("查看节点数据：" + new String(data));
    }


    @Test
    public void updateZNodeData() throws Exception {
        zk.setData("/zk", "newData".getBytes(), -1);
        byte[] data = zk.getData("/zk", false, null);
        System.out.println("修改后查看节点数据：" + new String(data));
    }

    //查看节点的子节点列表
    @Test
    public void getChildrenZNodes() throws Exception {
        zk.create("/zk/son", "sondate".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        List<String> children = zk.getChildren("/zk", false);
        for (String child : children) {
            System.out.println("查看节点的子节点列表: " + child);
        }
    }


    /**
     * 删除节点,备注:节点下不能有子节点,如果有子节点的,就无法删除
     */
    @Test
    public void deleteZNode() {
        try {
            zk.delete("/zk", -1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("删除znode节点成功");
    }


}
